<template>
  <div class="training">
    <header class="header">
      <button class="exit-btn" @click="exitTraining">退出</button>
    </header>
    
    <main class="main">
      <!-- 准备阶段倒计时 -->
      <PreparationPhase 
        v-if="isInPreparation" 
        @countdown-complete="startTrainingSession" 
      />
      
      <!-- 题目展示 -->
      <QuestionDisplay
        v-else
        ref="questionDisplayRef"
        :question="currentQuestion"
        :question-index="questionIndex"
        :total-questions="totalQuestions"
        :show-timer="isAnswerTimeLimited"
        :total-time="perQuestionTimeSeconds * 1000"
        :is-disabled="isAnswerSubmitted"
        @option-selected="handleOptionSelected"
      />
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { startTraining, answerQuestion } from '@/services/trainingService'
import PreparationPhase from '@/components/PreparationPhase.vue'
import QuestionDisplay from '@/components/QuestionDisplay.vue'

const isInPreparation = ref(true)
const currentQuestion = ref(null)
const sessionId = ref(null)
const questionIndex = ref(0)
const totalQuestions = ref(0)
const isAnswerSubmitted = ref(false)
const perQuestionTimeSeconds = ref(3)
const isAnswerTimeLimited = ref(false)
const moduleType = ref('')
const questionDisplayRef = ref(null)

const router = useRouter()


const startTrainingSession = async () => {
  try {
    // 从本地存储获取训练配置
    moduleType.value = localStorage.getItem('currentModuleType') || 'ARITHMETIC_QUIZ'
    const configStr = localStorage.getItem(`math_training_config_${moduleType.value}`)
    let trainingConfig = {
      trainingModeType: 'QUESTION_COUNT_LIMITED',
      questionCount: 20,
      questionType: 'ONE_DIGIT_ADDITION',
      optionCount: 3,
      perQuestionTimeSeconds: 3,
    }
    
    if (configStr) {
      trainingConfig = { ...trainingConfig, ...JSON.parse(configStr) }
    }
    
    // 设置闪卡模式相关参数
    isAnswerTimeLimited.value = moduleType.value === 'ARITHMETIC_FLASHCARD'
    perQuestionTimeSeconds.value = trainingConfig.perQuestionTimeSeconds || 3
    
    // 发送开始训练请求到后端
    const data = await startTraining({
      moduleType: moduleType.value,
      trainingConfig
    })
    
    sessionId.value = data.sessionId
    currentQuestion.value = data.firstQuestion
    questionIndex.value = 0
    totalQuestions.value = data.firstQuestion?.totalQuestions || 20
    
    // 切换到训练状态
    isInPreparation.value = false
  } catch (error) {
    console.error('开始训练失败:', error)
    alert('开始训练失败: ' + (error.message || '请重试'))
  }
}

// 处理选项选择事件
const handleOptionSelected = async (option) => {
  if (isAnswerSubmitted.value) return
  
  isAnswerSubmitted.value = true
  
  const startTime = Date.now() - (questionDisplayRef.value ? questionDisplayRef.value.elapsedTime : 0)
  const timeSpent = Date.now() - startTime
  
  try {
    // 提交答案到后端
    const data = await answerQuestion({
      sessionId: sessionId.value,
      questionId: currentQuestion.value.id,
      userAnswer: option,
      timeSpent
    })
    
    // 检查是否是最后一题
    if (!data.hasNextQuestion) {
      // 训练完成，跳转到结果页
      router.push('/result?sessionId=' + sessionId.value)
    } else {
      // 加载下一题
      currentQuestion.value = data.nextQuestion
      questionIndex.value++
      isAnswerSubmitted.value = false
      
      // Reset timer for next question
      if (questionDisplayRef.value) {
        questionDisplayRef.value.resetTimer()
      }
    }
  } catch (error) {
    console.error('提交答案失败:', error)
    alert('提交答案失败: ' + (error.message || '请重试'))
    isAnswerSubmitted.value = false
  }
}

const exitTraining = () => {
  if (confirm('确定要中止训练吗？')) {
    router.push('/')
  }
}

onMounted(() => {
  // Component automatically starts in preparation phase
})

onUnmounted(() => {
  // Cleanup handled by child components
})
</script>

<style scoped>
.training {
  min-height: 100vh;
  background-color: #f0f8ff;
}

.header {
  background-color: #4a90e2;
  color: white;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exit-btn {
  background: none;
  border: 1px solid white;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
}

.progress-info {
  font-size: 1.1rem;
}

.main {
  padding: 2rem;
  text-align: center;
  height: calc(100vh - 80px);
}
</style>